/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista;

import controladores.BancoJpaController;
import controladores.DetallenominaJpaController;
import controladores.EmpleadoJpaController;
import controladores.ParametrosJpaController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import modelo.Banco;
import modelo.Detallenomina;
import modelo.Empleado;
import modelo.Nomina;
import modelo.Parametros;

/**
 *
 * @author Ususario
 */
public class DialogNomina extends javax.swing.JDialog implements TableModelListener {

    List<String> empleados = new ArrayList<String>();
    private DefaultTableModel modelo1;
    String datos1[][] = {};
    BancoJpaController bC = new BancoJpaController();
    List<Banco> bancos;
    List<String> columnas1 = new ArrayList<String>();
    boolean nuevo = false;
    EmpleadoJpaController eC = new EmpleadoJpaController();
    private Nomina nomi;

    public DialogNomina(java.awt.Frame parent, boolean modal, Nomina n) {
        super(parent, modal);
        initComponents();
        columnas1.addAll(Arrays.asList(
                "Num id", "Empleado", "Tipo", "Sueldo mes",
                "Dias Trab.", "Dias Inc", "Sueldo Quincena",
                "Aux Transporte", "Sub Alimentación", "Incapacidades","Total devengado",
                "Salud", "Pension", "FSP", "Total pension", "Total Seg Soc", "ReteFuente"));

        bancos = bC.findBancoEntities();
        for (int i = 0; i < bancos.size(); i++) {
            columnas1.add(new String("" + bancos.get(i).getNombre()));
        }
        columnas1.add("Bancos");
        columnas1.add("Fondo Empl.");
        columnas1.add("Otros pagares");
        columnas1.add("Ami");
        columnas1.add("Recordar");
        columnas1.add("Seguros del estado");
        columnas1.add("Seguros bolivar");
        columnas1.add("Total seguros");
        columnas1.add("Total Deducido");
        columnas1.add("Neto a pagar");
        columnas1.add("Cargo");


        modelo1 = new DefaultTableModel(datos1, columnas1.toArray());
        nomi = n;
        List<Detallenomina> detallesNomina = n.getDetallenominaList();
        int i = 0;
        for (Detallenomina detallenomina : detallesNomina) {
            modelo1.addRow(new Object[]{});
            modelo1.setValueAt("" + detallenomina.getEmpleadoIdempleado().getCedula(), i, 0); //identificacion
            modelo1.setValueAt("" + detallenomina.getEmpleadoIdempleado().getNombre(), i, 1); //nombre
            modelo1.setValueAt("" + detallenomina.getEmpleadoIdempleado().getTipo(), i, 2); // Tipo
            modelo1.setValueAt("" + detallenomina.getEmpleadoIdempleado().getSalario(), i, 3); //sueldoMes
            modelo1.setValueAt("" + detallenomina.getDiastrabajados(), i, 4); // Dias trabajados
            modelo1.setValueAt("" + detallenomina.getDiasincapacidad(), i, 5); // Dias incapacidad
            modelo1.setValueAt("" + detallenomina.getSueldomes(), i, 6); // sueldo Quincena
            modelo1.setValueAt("" + detallenomina.getAuxTransporte(), i, 7); // aux transporte
            modelo1.setValueAt("" + detallenomina.getSubAlimenticio(), i, 8); // sub alimentacion
            modelo1.setValueAt("" + detallenomina.getIncapacidadLicencia(), i, 9); // total incapacidades/Licencias
            modelo1.setValueAt("" + detallenomina.getTotaldevengado(), i, 10); // Total devengado
            modelo1.setValueAt("" + detallenomina.getSalud(), i, 11); //Salud
            modelo1.setValueAt("" + detallenomina.getPension(), i, 12); //pension
            modelo1.setValueAt("" + detallenomina.getFsp(), i, 13); //FSP
            float totalpens = detallenomina.getFsp()+detallenomina.getPension();
            modelo1.setValueAt("" + totalpens, i, 14); //Total pension
            float totalss = detallenomina.getFsp()+detallenomina.getPension()+detallenomina.getSalud();
            modelo1.setValueAt("" + totalss, i, 15); //Total SS
            modelo1.setValueAt("" + detallenomina.getRetefuente(), i, 16); //Retefuente
            int j;
            for (j = 0; j < bancos.size(); j++) {
                modelo1.setValueAt("" + bancos.get(j).getNombre(), i, 17 + j);
            }
            modelo1.setValueAt("Bancos", i, 17 + j); //total bancos
            modelo1.setValueAt(detallenomina.getFondoempleado(), i, 18 + j); // fondo empleado
            modelo1.setValueAt("Otros pagares", i, 19 + j); // otros pagare
            modelo1.setValueAt("" + detallenomina.getAmi(), i, 20 + j); // ami
            modelo1.setValueAt("" + detallenomina.getRecordar(), i, 21 + j); // recordar
            modelo1.setValueAt("" + detallenomina.getSegurosestado(), i, 22 + j);//seguros del estado
            modelo1.setValueAt("" + detallenomina.getSegurosbolivar(), i, 23 + j); //seguros bolivar
            modelo1.setValueAt("Total seguros", i, 24 + j); // total seguros
            modelo1.setValueAt("Total Deducido", i, 25 + j); // total deducidos
            modelo1.setValueAt("Neto a pagar", i, 26 + j); // neto a pagar
            modelo1.setValueAt("" + detallenomina.getEmpleadoIdempleado().getCargoIdcargo().getCodigo(), i, 27 + j); // cargo

            i++;

        }


        masterTable.setModel(modelo1);
        masterTable.getModel().addTableModelListener(this);





    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setPreferredSize(new java.awt.Dimension(800, 370));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 225, Short.MAX_VALUE)
        );

        masterTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        masterTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane4.setViewportView(masterTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 1248, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(256, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 414, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DialogNomina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DialogNomina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DialogNomina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DialogNomina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        /*    java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
         DialogNomina dialog = new DialogNomina(new javax.swing.JFrame(), true, );
         dialog.addWindowListener(new java.awt.event.WindowAdapter() {
         @Override
         public void windowClosing(java.awt.event.WindowEvent e) {
         System.exit(0);
         }
         });
         dialog.setVisible(true);
         }
         });*/
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTable masterTable;
    // End of variables declaration//GEN-END:variables

    @Override
    public void tableChanged(TableModelEvent e) {
        int row = e.getFirstRow();
        int column = e.getColumn();
        Parametros pg = new ParametrosJpaController().findParametros(1);
        TableModel modelo2 = (TableModel) e.getSource();
        if (column == 4) {
            String dias = (String) modelo2.getValueAt(row, column);
            String sueldo = (String) modelo2.getValueAt(row, 3);
            String tipo = (String) modelo2.getValueAt(row, 2);

            int diasN = Integer.parseInt(dias);
            float sueldoM = Float.parseFloat(sueldo);
            float quincena = sueldoM * diasN / 30;
            modelo2.setValueAt("" + quincena, row, 6); // quincena

            if (sueldoM < pg.getSalariominimo() * 2) {
                float AuxTrans = pg.getAuxiliotransporte() * diasN / 30;
                modelo2.setValueAt("" + AuxTrans, row, 7);  //auxilio de transporte
            } else {
                modelo2.setValueAt("0.0", row, 7);
            }

            if (tipo.toLowerCase().equals("planta") && sueldoM < pg.getLimitesubalimentacion()) {
                float subAlim = pg.getSubsidioalimentacion() * diasN / 30;
                modelo2.setValueAt("" + subAlim, row, 8);  //subsidio de alimentacion
            } else {
                modelo2.setValueAt("0.0", row, 8);  //subsidio de alimentacion
            }
            
            String k = (String) modelo2.getValueAt(row, 6);
            float k1 = Float.parseFloat(k);
            String l = (String) modelo2.getValueAt(row, 7);
            float l1 = Float.parseFloat(l);
            String n = (String) modelo2.getValueAt(row, 8);
            float n1 = Float.parseFloat(n);
            String p = (String) modelo2.getValueAt(row, 9);
            float p1 = Float.parseFloat(p);
            float devengado = k1+l1+n1+p1;
            modelo2.setValueAt("" +devengado , row, 10);  //total devengado


            masterTable.setModel(modelo2);



        }




    }
}
